package gen.tools.modUnit;

import gen.tools.Widgets;
import gen.tools.structures.ModNode;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mailGenerator.MailGenerator;

public class ApproveApplyModDependency extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ApproveApplyModDependency() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		final boolean isApprove = Integer.parseInt(request.getParameter("isApprove"))==1?true:false;	//主管是否同意
		final int craId = wid.getParNumberFromRequest( request.getParameter("craId") );	//變更申請ID
		final int toDoListId = wid.getParNumberFromRequest( request.getParameter("toDoListId") );
		final String subsysId = request.getParameter("subsysId");
		final String applierId = request.getParameter("creatorId");
		final String empId = request.getParameter("empId");
		final int changeTypeId = (isApprove?11:12);
		
		/*
		 * 1. 檢查這筆資料是不是還在(沒有其它主管先回覆了) 
		 * 2. 異動jenkins的設定
		 * 3. 修改變更申請的狀態
		 * 4. 刪除todolist
		 * 	寄發通知信
		 **/
		
		String strSQL;
		String res = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			
			conn = wid.getConn();
			
			/****檢查有沒有其它主管先回覆了****/
			strSQL="SELECT craStatusId FROM cramain WHERE craId=?";
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, craId);
			rs = ps.executeQuery();
			rs.next();
			if ( rs.getInt(1)==10 ) {	//表示仍處於待審的狀態
				
				/****建立LOG，第一步就開始記錄程式的執行****/
				conn.setAutoCommit(false);
				strSQL="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,"+changeTypeId+",?,?)";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, empId);
				ps.setTimestamp(2, wid.cDT());
				ps.execute();
				strSQL="SELECT MAX(changeLogId) FROM changelog";
				ps = conn.prepareStatement(strSQL);
				rs = ps.executeQuery();
				rs.next();
				final int applyModDep = rs.getInt(1);
				conn.commit();
				conn.setAutoCommit(true);
				
				//修改變更申請的狀態
				strSQL = "UPDATE cramain SET craStatusId=? WHERE craId=?";
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, changeTypeId);
				ps.setInt(2, craId);
				ps.execute();
				
				//取得提出者的寄件地址
				final String mailList[] = wid.getEmailAddr(applierId);
				
				//刪除已完成的待辦事項，將其加入待辦清單
				wid.completedList(toDoListId, applierId);
		
				String mailSubject;
				String mailBody;
				MailGenerator mg = new MailGenerator();
				
				if ( isApprove ) {
					strSQL="SELECT t1.craDetId,t1.modUnitId,t2.modId FROM cradetail t1 LEFT JOIN cradependency t2 ON t2.craId=t1.craId AND t1.craId=t2.craId AND t1.craDetId=t2.craDetId WHERE t1.craId=?";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, craId);
					rs = ps.executeQuery();
					int preCraDetId=0;
					ArrayList<ModNode> arrModNode = new ArrayList<ModNode>();
					String currentNode="";
					String ds="";
					
					while (rs.next()) {
						if ( rs.getInt("craDetId") != preCraDetId) {
							if (arrModNode.size()!=0) {
								String tmp = arrModNode.get(arrModNode.size()-1).getDownSreamNode();
								if ( !"".equalsIgnoreCase(tmp) ){
									tmp = tmp.substring(0,tmp.length()-1);
									arrModNode.get(arrModNode.size()-1).setDownSreamNode(tmp);	
								}
							}
							
							preCraDetId = rs.getInt("craDetId");
							
							ModNode mn = new ModNode();
							currentNode=rs.getString("modUnitId");
							mn.setCurrentNode(currentNode);
							if ( rs.getString("modId")!=null ) {
								ds = rs.getString("modId")+",";	
							}
							mn.setDownSreamNode(ds);
							arrModNode.add(mn);
						} else {
							String tmp = arrModNode.get(arrModNode.size()-1).getDownSreamNode();
							tmp += rs.getString("modId")+",";
							arrModNode.get(arrModNode.size()-1).setDownSreamNode(tmp);	
						}
					}
					for (int i=0; i< arrModNode.size();i++){
						wid.setJobDownstreamOnJenkins(
								arrModNode.get(i).getDownSreamNode(),
								false,
								wid.JENKINSURL+"job/"+arrModNode.get(i).getCurrentNode()+"/config.xml","","");
					}
				}
				
				mailSubject = mg.subjectMail(isApprove?11:12);
				mailBody = mg.mailBodyMail(isApprove?11:12,wid.getEmpName(empId));
				
				//寄發通知信
				wid.sendMailMain(mailList, mailSubject, mailBody);
				
				/****完成這次的異動****/
				strSQL = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
				ps = conn.prepareStatement(strSQL);
				ps.setTimestamp(1, wid.cDT());
				ps.setInt(2, applyModDep);
				ps.execute();
				
				res="OK";
			}
		} catch(Exception e) {
			res = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write(res);
		
	}
}
